import { Component, Inject } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import * as qs from 'qs';
import { Subscription } from 'rxjs';
import IResult from 'src/app/pojo/IResult';
import IUser from 'src/app/pojo/IUser';
import { UserService } from 'src/app/service/user.service';
import { USERInjectionToken } from 'src/app/service/user.token';
@Component({
  selector: 'app-user-login',
  templateUrl: './user-login.component.html',
  styleUrls: ['./user-login.component.scss']
})
export class UserLoginComponent {

  model: IUser = { name: '22', password: '22' };

  // 用于释放订阅
  private subscriptions: Subscription[] = [];

  constructor(private route: Router, private userService: UserService,
    @Inject(USERInjectionToken) private user: IUser) { }

  // 组件初始化
  ngOnInit() {

  }


  onSubmit(form: NgForm): void {
    console.log(form.value);
    // 这里可以添加逻辑来验证用户输入并发送到后端
    if (form.valid) {
      // 模拟后端验证
      const name = form.value.name;
      const password = form.value.password;

      // 接口参数
      let payload = qs.stringify({
        name: name,
        password: password,
      });


      // 通过服务验证登录账号密码
       // alert('Login successful!');
            // 在这里可以重定向到其他页面
            // 导航到用户详情页面并传递参数
            //  1. 路径参数 (Path Parameters)
            //  this.router.navigate(['/userList', name]);
            // 2. 查询参数 (Query Parameters)
            //  this.router.navigate(['/usermanager'], { queryParams: { name: name, extraData: name } })
      const subscription = this.userService.login(payload).pipe(
         
      ).subscribe(
        {
          next: (result: IResult) => {
            const user = result.user;
            if(user && user.name){

              this.userService.setUser(user);
              localStorage.setItem('user', JSON.stringify(user));

              this.route.navigate(['/usermanager/userList'], { queryParams: { name: name, extraData: name } });

            }else{
              alert('登录失败:');
            }
            console.log(user);
          },
          error: (error) => {
            alert('登录失败:');
          },
          complete: () => {
            
          }
        }
      );
      this.subscriptions.push(subscription);
    }
  }
  logout(): void {
    this.userService.setUser(null);
    localStorage.removeItem('user');
  }
  
  // 组件销毁
  ngOnDestroy(): void {
    // 释放内存订阅器
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }
}
